package com.tp.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
/**
 * 路径处理工具
 * 
 */
public class PathUtils {

	private static final String DEFAULT_CHARSET = "UTF-8";

	/**
	 * 获取完整请求路径(含内容路径及请求参数)
	 * 
	 * @param request
	 * @return
	 */
	public static String getRequestURIWithParam(HttpServletRequest request) {
		return request.getRequestURI() + (request.getQueryString() == null ? "" : "?" + request.getQueryString());
	}
	
	/**
	 * 获取上下文URL全路径
	 * @param request
	 * @return
	 */
	public static String getContextPath(HttpServletRequest request) {
		StringBuilder sb = new StringBuilder();
		int port = request.getServerPort();
		if (80 == port) {
			sb.append(request.getScheme()).append("://").append(request.getServerName())
					.append(request.getContextPath());
		} else {
			sb.append(request.getScheme()).append("://").append(request.getServerName()).append(":").append(port)
					.append(request.getContextPath());
		}

		String path = sb.toString();
		return path;
	}
	
	public static String rebuild(String path) {
		String newPath = path;
		try {
			newPath =  URLDecoder.decode(newPath, DEFAULT_CHARSET);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		newPath = rebuildNoDecode(newPath);
		
		return newPath;
	}
	
	public static String rebuildNoDecode(String path) {
		String newPath = path;
		newPath = newPath.replaceAll("\\\\", "/");
		newPath = newPath.replaceAll("//", "/");
		
		return newPath;
	}
}
